import React, { useState, useEffect, useRef } from 'react';
import AudioPlay from './AudioPlay';
import AudioButton from './AudioButton';

export default function BGM({ playState }) {
    const [audioPermission, setAudioPermission] = useState(true);
    const [beginState, setBeginState] = useState(false);
    const beginAudioElem = useRef(null);
    const beginPlay = () => {
        setBeginState(true);
    };
    const beginPause = () => {
        setBeginState(false);
    };

    const [bgState, setBgState] = useState(true);
    const bgAudioElem = useRef(null);
    const bgPlay = () => {
        setBgState(true);
    };
    const bgPause = () => {
        setBgState(false);
    };

    useEffect(() => {
        if (audioPermission) {
            if (playState) {
                bgAudioElem.current.pause && bgAudioElem.current.pause();
                beginAudioElem.current.play && beginAudioElem.current.play();
            } else {
                beginAudioElem.current.pause && beginAudioElem.current.pause();
                bgAudioElem.current.play && bgAudioElem.current.play();
            }
        } else {
            bgAudioElem.current.pause && bgAudioElem.current.pause();
            beginAudioElem.current.pause && beginAudioElem.current.pause();
        }
    }, [bgState, beginState, audioPermission, playState]);

    const clickHandle = () => {
        if (beginState || bgState) {
            setAudioPermission(false);
            setBeginState(false);
            setBgState(false);
        } else {
            setAudioPermission(true);
            if (playState) {
                setBeginState(true);
                setBgState(false);
            } else {
                setBeginState(false);
                setBgState(true);
            }
        }
    };

    return (
        <>
            <AudioPlay id="audiobegin" elem={beginAudioElem} audioSrc="https://imgcdn.huanjutang.com/assets/img/20211261414518081.mp3" onPlay={beginPlay} onPause={beginPause} />
            <AudioPlay id="audiobg" elem={bgAudioElem} audioSrc="https://imgcdn.huanjutang.com/assets/img/20211261414517887.mp3" onPlay={bgPlay} onPause={bgPause} />
            <AudioButton hasPlayed={ beginState || bgState } clickHandle={clickHandle} />
        </>
    )
}